// login & register
const express = require('express')
const router = express.Router()
const User = require('../../models/User')
const bcrypt = require('bcrypt')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const key = require("../../config/keys").secretOrKey
const passport = require('passport')


// $route POST api/users/register
// @desc 返回请求的json数据
// @access public
router.post("/register", (req, res) => {
    console.log(req.body)
    if (!req.body.name || !req.body.email || !req.body.password || !req.body.identity) return res.status(400).json({msg: '用户名，邮箱，密码不能为空'})

    // 查询数据库中是否拥有邮箱
    User.findOne({email: req.body.email})
    .then((user)=> {
        if (user) {
            return res.status(400).json({msg: '邮箱已被注册'})
        } else {
            const avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'})
            const newUser = new User({
                name: req.body.name,
                email: req.body.email,
                avatar,
                password: req.body.password,
                identity: req.body.identity
            })

            bcrypt.genSalt(10, function(err, salt) {
                bcrypt.hash(req.body.password, salt, (err, hash) => {
                    if (err) throw err
                    newUser.password = hash

                    newUser.save()
                    .then(user => res.json(user))
                    .catch(err => res.status(500).json({msg: '数据库保存失败'}))
                });
            });
            
        }
    })
    .catch(err => res.status(500).json({msg: '数据库查询失败'}))
})

// $route POST api/users/login
// @desc 返回token jwt passport
// @access public
router.post("/login", (req, res) => {
    const email = req.body.email
    const password = req.body.password
    if (!email || !password) return res.status(400).json({msg: '用户名，密码不能为空'})
    // 查询数据库
    User.findOne({email})
    .then(user => {
        if(!user) {return res.status(404).json({msg: '用户不存在'})}

        // 密码匹配
        bcrypt.compare(password, user.password, (err, result) => {
            if (err || !result) {return res.status(400).json({msg: '密码错误'})}
            const rule = {id: user.id, name: user.name, avatar:user.avatar, identity: user.identity}
            jwt.sign(rule, key, {expiresIn: 3600 * 24}, (err, token) => {
                if (err) throw err
                return res.json({token: 'Bearer ' + token, success: true})
            })
        });

    })
    .catch(err => res.status(500).json({msg: '数据库查询失败'}))
})

// $route GET api/users/current
// @desc 返回 当前用户
// @access Private
router.get('/current', passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email,
        avatar: req.user.avatar,
        identity: req.user.identity
    })
})

module.exports = router
